﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Collections.Concurrent;
using System.Net;

namespace Nina
{
    public class NinaSession
    {
        private Socket m_socket;
        private List<byte[]> m_writeBuffer;
        private List<byte> m_readBuffer;
        private ConcurrentDictionary<string, object> m_properties;
        private bool m_close;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="socket">The underlying socket of the session</param>
        public NinaSession(Socket socket)
        {
            m_socket = socket;
            m_socket.ReceiveTimeout = 1000;
            m_socket.SendTimeout = 1000;
            m_socket.NoDelay = true;
            m_writeBuffer = new List<byte[]>();
            m_readBuffer = new List<byte>();
            m_close = false;
            m_properties = new ConcurrentDictionary<string, object>();
        }

        /// <summary>
        /// Returns local IP address
        /// </summary>
        public static string LocalIPAddress
        {
            get
            {
                /* Lookup local address */
                IPHostEntry host;
                string hostIp = null;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily.ToString() == "InterNetwork")
                    {
                        hostIp = ip.ToString();
                    }
                }
                /* No address found, bind to localhost */
                if (hostIp == null)
                    hostIp = "127.0.0.1";

                return hostIp;
            }
        }

        /// <summary>
        /// Returns the next array of bytes read from the socket
        /// </summary>
        public byte[] Read()
        {
            List<byte> result = new List<byte>();

            if (m_readBuffer.Count > 0)
            {
                result.AddRange(m_readBuffer);
                m_readBuffer.Clear();
            }

            /* Build a buffer and read data */
            if (IsConnected)
            {
                byte[] buffer = new byte[m_socket.Available];
                int amount = 0;
                if (buffer.Length > 0)
                {
                    try
                    {
                        amount = m_socket.Receive(buffer, buffer.Length, 0);
                    }
                    catch (Exception e) { }

                    if (amount != buffer.Length)
                    {
                        for (int i = 0; i < amount; i++)
                        {
                            result.Add(buffer[i]);
                        }
                    }
                    else
                    {
                        result.AddRange(buffer);
                    }
                }
            }

            return result.ToArray<byte>();
        }

        /// <summary>
        /// Writes data asynchronously to the remote host
        /// </summary>
        public void Write(byte [] data)
        {
            m_writeBuffer.Add(data);
        }

        /// <summary>
        /// Flushes data to the remote address - i.e. no queuing
        /// Note: This method immediately flushes bytes without them
        /// being processed by any codecs. It is mainly used by the library.
        /// Use with caution.
        /// </summary>
        /// <returns>True on success</returns>
        public bool Flush(byte [] data)
        {
            try
            {
                int dataSent = 0;
                while (dataSent != data.Length)
                {
                    dataSent += m_socket.Send(data, data.Length, 0);
                }
                return true;
            }
            catch (Exception e)
            {
            }
            return false;
        }

        /// <summary>
        /// Closes the session asynchronously
        /// </summary>
        public void Close()
        {
            m_close = true;
            try
            {
                m_socket.Shutdown(SocketShutdown.Both);
            }
            catch { }
        }

        /// <summary>
        /// Attempts to immediately close the session
        /// provided the Close() method has already been called
        /// </summary>
        public void AttemptClose()
        {
            if (m_close && m_writeBuffer.Count == 0)
            {
                m_socket.Close();
            }
        }

        /// <summary>
        /// Returns true if there is data to be read
        /// </summary>
        public bool CanRead
        {
            get
            {
                return m_socket.Available != 0 || m_readBuffer.Count != 0;
            }
        }

        /// <summary>
        /// Returns true if there is data to write
        /// </summary>
        public bool CanWrite
        {
            get
            {
                return m_writeBuffer.Count > 0;
            }
        }

        /// <summary>
        /// Returns true if the session is connected
        /// </summary>
        public bool IsConnected
        {
            get
            {
                return m_socket.Connected;
            }
        }

        /// <summary>
        /// Session properties
        /// </summary>
        public ConcurrentDictionary<string, object> Properties
        {
            get
            {
                return m_properties;
            }
        }

        /// <summary>
        /// Returns the write queue
        /// </summary>
        public List<byte[]> WriteBuffer
        {
            get
            {
                return m_writeBuffer;
            }
        }

        public List<byte> ReadBuffer
        {
            get
            {
                return m_readBuffer;
            }
        }
    }
}
